package org.ruiyichen.guizhou.agr.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.google.gson.reflect.TypeToken;

import org.ruiyichen.guizhou.agr.R;
import org.ruiyichen.guizhou.agr.base.BaseActivity;
import org.ruiyichen.guizhou.agr.base.DataManger;
import org.ruiyichen.guizhou.agr.bean.Response;
import org.ruiyichen.guizhou.agr.bean.mode.IIrrigatedAreaModel;
import org.ruiyichen.guizhou.agr.config.Constant;
import org.ruiyichen.guizhou.agr.net.OkHttpManager;
import org.ruiyichen.guizhou.agr.ui.adapter.IrrigatedAreaRecyclerAdapter;
import org.ruiyichen.guizhou.agr.ui.listener.OnRecyclerItemClick;
import org.ruiyichen.guizhou.agr.ui.mineview.BToast;
import org.ruiyichen.guizhou.agr.ui.mineview.CustomDialog;
import org.ruiyichen.guizhou.agr.utils.ListUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * Created by Administrator on 2018/9/8.
 */

public class IrrigatedAreaManageActivity extends BaseActivity implements View.OnClickListener {
    public static final String TAG_ID = "id";
    /**
     * 当前状态
     */
    private boolean isEdit = true;

    private RecyclerView rv_nf_info_root;


    private IrrigatedAreaRecyclerAdapter adapter;

    private List<IIrrigatedAreaModel> list = new ArrayList<>();


    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.df_activity_irrigated_area_manage);
        bOkHttpManager = new OkHttpManager(this, bHandler);
        initData();
    }

    @Override
    protected void initViews() {
        setTitle("灌区管理").setRightImage(0).setRightText(isEdit ? "编辑" : "保存");
        rv_nf_info_root = findViewById(R.id.rv_home_control);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setAutoMeasureEnabled(true);
        rv_nf_info_root.setLayoutManager(manager);
        rv_nf_info_root.setNestedScrollingEnabled(false);


//        list.add(new IIrrigatedAreaModel(false, "默认区域（0个设备）", false));
//        list.add(new IIrrigatedAreaModel(false, "东边1#灌区（2个设备）", true));

        adapter = new IrrigatedAreaRecyclerAdapter(this);
        adapter.setmDatas(list);
        rv_nf_info_root.setAdapter(adapter);
    }

    @Override
    protected void initEvents() {
        findViewById(R.id.iv_normal_back).setOnClickListener(this);
        findViewById(R.id.tv_add_irrigated_area).setOnClickListener(this);
        findViewById(R.id.tv_normal_other).setOnClickListener(this);
        adapter.setOnRecyclerItemClick(new OnRecyclerItemClick() {
            @Override
            public void onItemClick(View view, final int position) {
                if (list.get(position).getIIsDelete()) {
                    //删除
                    CustomDialog dialog = new CustomDialog.Builder(IrrigatedAreaManageActivity
                            .this, CustomDialog.Style.MULTI_TIPS)
                            .setTitle("温馨提示")
                            .setMessage("是否删除该灌区？")
                            .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    if (position >= 0 && position < list.size()) {
                                        IIrrigatedAreaModel iIrrigatedAreaModel = list.get(position);
                                        deleteIrrigateArea(iIrrigatedAreaModel);
                                    }
                                }
                            })
                            .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).setTitle("提示")
                            .create();
                    dialog.show();
                    return;
                }
                if (list.get(position).hasIDevice()) {
                    //灌区设备控制
                    Intent it = new Intent(IrrigatedAreaManageActivity.this,
                            IrrigatedDeviceControlActivity.class);
                    it.putExtra(IrrigatedDeviceControlActivity.PAGE_TITLE, list.get(position).getIIrrigatedAreaDesc());
                    it.putExtra(IrrigatedDeviceControlActivity.TAG_ID, list.get(position).irrigId);
                    it.putExtra(Constant.ParamKey.IRRIGATED_AREA, list.get(position));
                    startActivity(it);
                    return;
                }
                //默认设备
                Intent it = new Intent(IrrigatedAreaManageActivity.this, DefaultDeviceActivity
                        .class);
                it.putExtra(DefaultDeviceActivity.TAG_ID, list.get(position).irrigId);
                startActivity(it);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_normal_back:
                onBackPressed();
                break;
            case R.id.tv_add_irrigated_area:
                //删除
                CustomDialog dialog = new CustomDialog.Builder(this, CustomDialog.Style.MULTI_TIPS)
                        .setTitle("温馨提示")
                        .setMessage("是否新增灌区")
                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent it = new Intent(IrrigatedAreaManageActivity.this,
                                        AddIrrigatedAreaActivity.class);
                                startActivity(it);
                            }
                        })
                        .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).setTitle("提示")
                        .create();
                dialog.show();
                break;
            case R.id.tv_normal_other:
                isEdit = !isEdit;
                setRightText(isEdit ? "编辑" : "保存");
                //显示删除
                adapter.setIsEdit(!isEdit);
                if (!isEdit) {
                    //保存
                    submit();
                }
                break;
        }
    }

    private void initData() {
        //http://localhost/dev-api/asset/irrig/list?pageNum=1&pageSize=10
        Map<String, String> body = new HashMap<>();
        body.put("pageNum", "1");
        body.put("pageSize", "10");
        bOkHttpManager.httpRequest(Constant.RequestType.GET_IRRIGATED_LIST, Constant.Http.GET, body, false, new
                TypeToken<Response<Void, ArrayList<IIrrigatedAreaModel>>>() {
                }.getType(), true, false);
    }

    private void deleteIrrigateArea(IIrrigatedAreaModel iIrrigatedAreaModel) {
        Map<String, String> body = new HashMap<>();
        body.put("irrigId", iIrrigatedAreaModel.irrigId);
        bOkHttpManager.httpRequest(Constant.RequestType.UPDATE_DELETE_IRRIG, Constant.Http.POST, body, false, new
                TypeToken<Response<Void, Void>>() {
                }.getType(), true, false);
    }


    /**
     * 提交
     */
    private void submit() {
        Map<String, String> body = new HashMap<>();
//        token	String	登录成功返回的token
        body.put("token", DataManger.getInstance().getUserInfo().token);

        bOkHttpManager.httpRequest(Constant.RequestType.SEND_MESSAGE, Constant.Http.POST, body, false, new
                TypeToken<Response<Void, Void>>() {
                }.getType(), true, false);
    }

    @Override
    protected void onPostHandle(int requestType, Object response, boolean error, int errorCode, Object obj1, Object obj2) {
        super.onPostHandle(requestType, response, error, errorCode, obj1, obj2);
        if (error) {
            BToast.getInstance().show(getResources().getString(R.string.abnormal));
        } else {
            if (response == null) {
                BToast.getInstance().show(getResources().getString(R.string.datafailure));
            } else {
                if (requestType == Constant.RequestType.GET_IRRIGATED_LIST) {
                    Response<Void, List<IIrrigatedAreaModel>> result = (Response<Void, List<IIrrigatedAreaModel>>) response;
                    if (result.isSuccess()) {
                        list.clear();
                        if (ListUtil.isNotEmpty(result.getRows())) {
                            list.addAll(result.getRows());
                        }
                        adapter.notifyDataSetChanged();
                    } else {
                        BToast.getInstance().show(result.getMsg());
                    }
                } else if (requestType == Constant.RequestType.UPDATE_DELETE_IRRIG) {
                    Response<Void, Void> result = (Response<Void, Void>) response;
                    if (result.isSuccess()) {
                        isEdit = true;
                        setRightText(isEdit ? "编辑" : "保存");
                        initData();
                    }
                    BToast.getInstance().show(result.getMsg());
                }
            }
        }
    }

}
